<template>
  <el-form-item :label="label" :prop="prop">
    <el-upload
      action=""
      :list-type="ListType(type)"
      :accept="acceptFile"
      :multiple="multiple"
      :limit="limitNum"
      :auto-upload="false"
      :on-exceed="handleExceed"
      :before-upload="beforeUpdata"
      :on-change="handleChange"
      :file-list="uploadFileList"
      :on-remove="Remove"
      :on-success="uploadSuccess"
      :class="{ hide: hideUpload }"
      :http-request="handlePost"
    >
      <template #default>
        <el-button size="small" v-if="![1, 2, 3, 6].includes(type)" type="text" :plain="uploadName">{{ uploadName || '上传文件' }}</el-button>
        <div>
          <el-icon class="upload_icon" v-if="[1, 2, 3].includes(type)"><plus /></el-icon>
          <div class="upload_icon_text">添加图片</div>
        </div>
        <el-button size="small" v-if="[6].includes(type)" :plain="uploadName">{{ uploadName || '上传文件' }}</el-button>
        <!-- 添加插槽 -->
        <slot></slot>
      </template>
      <template #file="{ file }" v-if="![4, 5, 6].includes(type)">
        <div class="file_upload_box">
          <el-image style="el-upload-list__item-actions" :src="file.url" fit="cover"> </el-image>
          <el-icon class="del_icon" @click="handleRemove(file)"><DeleteFilled /></el-icon>
        </div>
      </template>
      <template #tip>
        <div class="el-upload__tip">
          <!-- <span v-if="type == 1">单张图片大小不超过{{props.upInfo.limitSize}}M，支持png；jpg；jpeg；gif等格式，图片宽度不超过1440px,高度不超过1080px</span> -->
          <span v-if="type == 1">{{limitSizeCover}}</span>
          <span v-else-if="type == 2">格式支持DOC、DOCX、XLS、XLSX、CSV、PPT、PPTX、TXT、PDF及Xmind格式，文件大小不超过20M</span>
          <span v-else-if="type == 3">格式支持mp4，文件大小不超过10M</span>
          <span v-else-if="type == 4">格式支持mp3、wma、wav、amr、m4a，文件大小不超过200M，音频时长不超过2小时。</span>
        </div>
      </template>
    </el-upload>
  </el-form-item>
</template>
<script setup lang="ts">
  import { ref, reactive, defineProps, onUnmounted, computed } from 'vue'
  import { ElForm, ElMessage } from 'element-plus'
  import type { UploadProps, UploadUserFile } from 'element-plus'
  import { Plus, ZoomIn, Download, Delete } from '@element-plus/icons-vue'
  import type { UploadFile } from 'element-plus/es/components/upload/src/upload'
  import { uploadFile2 } from '@/api/common'
  import { getSetionId, getImage_wh, getSuffixIcon, IsNotEmpty } from '@/utils/utils'
  import bus from '@/utils/bus'
  const emit = defineEmits(['submit'])

  const formRef = ref<InstanceType<typeof ElForm>>()
  const dialogImageUrl = ref('')
  const dialogVisible = ref(false)
  const uploadFileList = ref<UploadUserFile[]>([])
  const ListType = (val: number) => {
    switch (val) {
      case 1:
      case 2:
      case 3:
        return 'picture-card'
      case 4:
        return 'text'
      default:
        return 'text'
    }
  }
  const limitSizeCover = computed(() => {
    return props.upInfo.limitSizeCover||'图片支持JPG、PNG、JPEG格式，大小2M以内，建议宽高比为1：1，尺寸200px*200px'
  })
  const props = defineProps<{
    upInfo: {
      type: number //文件类型
      label: string //文件名称
      prop: string // 是否是必传
      files: any //文件
      multiple: {
        //是否支持多选
        type: boolean
        default: false
      }
      limitSize: number // 最大文件上传限制
      limitNum: {
        // 上最大传数量
        type: number
        default: 1
      }
      uploadName: ''
      acceptFile: string // 上传类型文件判断
      limitSizeCover: string
    }
  }>()
  //  type: 1 图片  2 文件 3 视频 4 语音 5 Excell
  const { type, label, prop, files, multiple, limitSize, acceptFile, limitNum, uploadName } = props.upInfo
  const beforeUpdata = async (file: any) => {
    let is2M = file.size / 1024 / 1024 <= limitSize
    let tips = '视频'
    switch (type) {
      case 1:
        tips = '图片'
        const { W, H } = await getImage_wh(file)
        let ext = file.name.substring(file.name.lastIndexOf('.'))
        const isImge = acceptFile.indexOf(ext) == -1
        is2M = file.size / 1024 / 1024 <= 2
        if (isImge) {
          ElMessage.warning(`该图片是${ext}格式,请上传${acceptFile}格式图片`)
          return false
        }
        if (!is2M) {
          ElMessage.warning(`图片大小最大支持2M`)
          return false
        }
        // if (W > 1440) {
        //   ElMessage.warning(`该图片宽度${W}px,超过最大图片尺寸宽度1440px`)
        //   return false
        // }
        // if (H > 1080) {
        //   ElMessage.warning(`该图片高度${H}px,超过最大图片尺寸高度1080px`)
        //   return false
        // }
      case 2:
        tips = '文件'
        break
      case 3:
        tips = '视频'
        break
      case 4:
        tips = '语音'
        break
      default:
        tips = ''
    }
    if (!is2M) {
      ElMessage.warning(`上传的${tips}最大支持${limitSize}M`)
    }
    return is2M
  }
  const hideUpload = computed(() => {
    return uploadFileList.value.length >= limitNum
  })
  const handleRemove = (file: UploadFile) => {
    if (file.url) {
      uploadFileList.value = uploadFileList.value.filter((item: any) => item.url != file.url)
    } else {
      uploadFileList.value = (uploadFileList.value.length > 0 && uploadFileList.value.pop()) || []
    }
    console.log(uploadFileList.value, '---手动删除')
    emit('submit', uploadFileList.value)
  }
  const Remove: UploadProps['onRemove'] = (file: UploadFile, list: UploadFile[]) => {
    console.log(file, list, '--自动删除')
    uploadFileList.value = list
    emit('submit', list)
    // bus.emit('empty')
  }
  // 上传文件
  const uploadImg = async (file: any) => {
    file = file.raw
    let flag = await beforeUpdata(file)
    if (!flag) return
    return await uploadFile2({
      file,
      fileName: file.name
    })
  }
  // 自定义上传
  const handlePost = (file: any) => {}
  // 上传成功
  const uploadSuccess = (res: any, file: UploadFile, list: UploadFile[]) => {}
  // 上传改变
  const handleChange = async (file: UploadFile, list: UploadFile[]) => {
    let existFile = list.slice(0, list.length - 1).find((f) => f.name === file.name)
    if (existFile) {
      ElMessage.error('当前文件已经存在!')
      list.pop()
      return
    }

    // 话术Excell导入 不调用接口
    if (type == 5) {
      emit('submit', file)
      return
    }
    const data: any = await uploadImg(file)
    // 上传被拦截
    if (!IsNotEmpty(data)) {
      list.pop()
      return
    }
    // 文件
    if (type == 2) {
      uploadFileList.value.push({
        realurl: data.url,
        code: data.code,
        url: getSuffixIcon(data.url),
        name: file.name
      })
    } else {
      uploadFileList.value.push(data)
    }
    emit('submit', uploadFileList.value)
  }

  const handleExceed = (file: UploadFile, list: UploadFile[]) => {
    ElMessage.warning(`当前限制选择 ${limitNum} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + list.length} 个文件`)
  }
  // 图片数据回显
  const echo = (data: any, isFllow?: any) => {
    if (!isFllow) {
      if (type == 1) {
        if (data.cover_image_url) {
          uploadFileList.value.push({ url: data.cover_image_url })
        } else {
          data.forEach((item: any) => {
            uploadFileList.value.push({ url: item.absolute_url })
          })
        }
      } else if (type == 4) {
        uploadFileList.value.push({ name: data.title, url: '/static/file/mp3.png' })
      }
    } else {
      if (data.length > 0) {
        uploadFileList.value = []
        data.forEach((item: any) => {
          if (item.type == 1) {
            uploadFileList.value.push({ url: item.url, code: item.code })
          } else {
            uploadFileList.value.push({ url: getSuffixIcon(item.url), code: item.code })
          }
        })
      }
    }
    return
  }
  // 清空数据回显
  const empty = () => {
    uploadFileList.value = []
  }
  bus.on('echo', echo)
  bus.on('empty', empty)
  const handlePictureCardPreview = (file: UploadFile) => {
    dialogImageUrl.value = file.url!
    dialogVisible.value = true
  }
  // 下载
  const handleDownload = (file: UploadFile) => {}
  // 主动暴露方法
  defineExpose({ empty, echo })
  onUnmounted(() => {
    bus.off('echo', echo)
    bus.off('empty', empty)
  })
</script>
<style lang="scss" scoped>
  .pre_img_box {
    overflow: hidden;
    .pre_image {
      display: block;
      margin: auto;
      max-height: 400px;
    }
  }
  :deep .el-upload--picture-card {
    width: 110px;
    height: 110px;
    text-align: center;
    padding-top: 10px;

    .upload_icon {
      height: 20px;
      text-align: center;
      font-size: 20px;
      color: #ff6b00;
    }
    .upload_icon_text {
      font-size: 14px;
      font-family: STHeitiSC-Light, STHeitiSC;
      font-weight: 300;
      color: #ff6b00;
    }
  }
  :deep .el-upload-list__item {
    width: 110px;
    height: 110px;
    display: inline-block;
    .file_upload_box {
      position: relative;
      width: 100%;
      height: 100%;
      .del_icon {
        position: absolute;
        right: 10px;
        top: 10px;
        cursor: pointer;
      }
    }
  }
  .el-upload__tip {
    margin-top: 10px;
    font-size: 12px;
    line-height: 1.4;
    color: #999;
  }
</style>
<style>
  .hide .el-upload--picture-card {
    display: none;
  }
  /* .upload_icon {
    width: 140px;
    height: 90px;
  } */
</style>
